package com.macro.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.macro.admin.config.security.JwtTokenUtil;
import com.macro.admin.dao.RoleDao;
import com.macro.admin.pojo.Admin;
import com.macro.admin.dao.AdminDao;
import com.macro.admin.pojo.AdminLoginParam;
import com.macro.admin.pojo.RespBean;
import com.macro.admin.pojo.Role;
import com.macro.admin.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author Xiao Hai
 * @since 2021-04-19
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminDao, Admin> implements AdminService {

    @Resource
    private AdminDao adminDao;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private RoleDao roleDao;

    /**
     * 登录返回token
     * @param username
     * @param password
     * @param code
     * @param phone
     * @param smsCode
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username,String password,String code,String phone,String smsCode, HttpServletRequest request) {

        UserDetails userDetails;

        if (null != phone){
            //创建redis对象
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String phoneCode = null;
            try {
                //获取redis值转成String类型
                phoneCode  = valueOperations.get(phone).toString();
            } catch (NullPointerException e){
                return RespBean.error("请先获取验证码!");
            }

            if (!phoneCode.equals(smsCode) || StringUtils.isEmpty(phoneCode)) {
                return RespBean.error("无效验证码!");
            }
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);

            Admin admin = adminDao.selectOne(wrapper);

            userDetails = userDetailsService.loadUserByUsername(admin.getUsername());

        }else {
            //从session中获取验证码
            String captcha = (String) request.getSession().getAttribute("captcha");

            if (StringUtils.isEmpty(code) || !captcha.equals(code)) {
                return RespBean.error("验证码填写错误!");
            }
            //登录
            userDetails = userDetailsService.loadUserByUsername(username);
            if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
                return RespBean.error("用户名或密码不正确！");
            }
            if (!userDetails.isEnabled()) {
                return RespBean.error("账号被禁用，请联系管理员！");
            }
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功", tokenMap);

    }

    /**
     * 获取当前登录用户信息
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        //创建查询对象
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        //放入查询条件
        queryWrapper.eq("username",username);
        Admin admin = adminDao.selectOne(queryWrapper);
        //admin.setPassword(null);
        //获取权限信息
        admin.setRoles(roleDao.getRole(admin.getId()));
        return admin;
    }

    /**
     * 根据用户id查询角色
     * @param adminId 用户id
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleDao.getRole(adminId);
    }

}
